package com.yeskery.nut.aop.aspect.parser;

import com.yeskery.nut.aop.aspect.BasePrefixMatchJoinParser;
import com.yeskery.nut.aop.aspect.JoinPoint;
import com.yeskery.nut.aop.aspect.joinpoint.AnnotationArgsJoinPoint;
import com.yeskery.nut.core.AntPath;
import com.yeskery.nut.util.StringUtils;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 基于方法参数类是否含有指定注解的连接点解析器
 * @author Yeskery
 * 2023/8/8
 */
public class AnnotationArgsJoinPointParser extends BasePrefixMatchJoinParser {

    @Override
    @SuppressWarnings("unchecked")
    public JoinPoint createJoinPoint(String value) {
        String express = getExpress(value);
        if (StringUtils.isEmpty(express.trim())) {
            return new AnnotationArgsJoinPoint(Collections.emptyList());
        }
        String[] splits = express.split(",");
        if (splits.length == 0) {
            return new AnnotationArgsJoinPoint(Collections.emptyList());
        }
        List<Class<? extends Annotation>> classes = new ArrayList<>(splits.length);
        for (String split : splits) {
            if (AntPath.PATTERN_SYMBOL.equals(split.trim())) {
                classes.add(Annotation.class);
            } else {
                Class<?> annotationClass = parseClass(split.trim());
                if (!Annotation.class.isAssignableFrom(annotationClass)) {
                    throw new IllegalArgumentException("Only Support Annotation Class, Current Class[" + annotationClass.getName() + "] Invalid.");
                }
                classes.add((Class<? extends Annotation>)annotationClass);
            }
        }
        return new AnnotationArgsJoinPoint(classes);
    }

    @Override
    protected String getPrefix() {
        return "@args";
    }
}
